<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers;

use api\modules\admin\models\LoginForm;
use api\utils\libs\BaseController;
use common\extend\exception\ErrorCode;
use Yii;


class PublicController extends BaseController
{
    /**
     * 生成滑块验证码
     * @return array
     */
    public function actionCaptcha(): array
    {
        $session = Yii::$app->session;
        
        // 生成随机拼图块位置
        $blockX = rand(50, 270);
        $blockY = rand(20, 110);
        
        // 生成唯一标识
        $uuid = md5(uniqid('slider_', true) . time());
        
        // 将位置信息存储在session中，5分钟有效期
        $session->set('slider_captcha_' . $uuid, [
            'blockX' => $blockX,
            'blockY' => $blockY,
            'time' => time(),
            'used' => false
        ]);
        
        return $this->success('', [
            'uuid' => $uuid,
            'blockY' => $blockY, // 前端需要知道Y坐标来定位拼图块
        ]);
    }
    
    /**
     * 验证滑块验证码
     * @return array
     */
    public function actionVerifySlider(): array
    {
        $token = $this->request->post('token', '');
        $blockX = (int)$this->request->post('blockX', 0);
        $duration = (int)$this->request->post('duration', 0);
        $trail = $this->request->post('trail', []);
        
        if (empty($token)) {
            return $this->error('验证参数不完整');
        }
        
        // 解码token
        $decoded = base64_decode($token);
        $parts = explode('_', $decoded);
        
        if (count($parts) < 2) {
            return $this->error('验证码格式错误');
        }
        
        $expectedX = (int)$parts[0];
        $timestamp = isset($parts[1]) ? (int)$parts[1] : 0;
        
        // 检查时间是否合理 (300ms - 10s)
        if ($duration < 300 || $duration > 10000) {
            return $this->error('验证失败，请重试');
        }
        
        // 检查时间戳是否在合理范围内（10分钟内）
        if (time() - $timestamp > 600) {
            return $this->error('验证已过期，请刷新重试');
        }
        
        // 验证位置准确性（允许5px误差）
        $accuracy = 5;
        if (abs($blockX - $expectedX) > $accuracy) {
            return $this->error('验证失败，请重试');
        }
        
        // 简单验证轨迹（检查是否有轨迹数据）
        if (!is_array($trail) || count($trail) < 5) {
            return $this->error('验证失败，请重试');
        }
        
        // 生成验证通过的凭证
        $verifyToken = md5($token . time() . $this->app->params['md5_secret_key']);
        
        // 存储验证凭证到session，5分钟有效期
        $session = Yii::$app->session;
        $session->set('slider_verify_' . $verifyToken, [
            'time' => time(),
            'verified' => true
        ]);
        
        return $this->success('验证成功', ['verifyToken' => $verifyToken]);
    }

    /**
     * 登录
     * @return array
     */
    public function actionLogin(): array
    {
        $model = new LoginForm();
        if (!$model->load($this->request->post(), '')) return $this->error('未获取到数据');
        $token = $model->login();
        if (!$token) return $this->error($model->error ?: '登录失败');
        return $this->success('登录成功', ['token' => $token]);
    }

    public function actions(): array
    {
        return [
            'upload-file' => [
                'class' => 'common\actions\UploadAction',
                'type' => 'file',
                'success' => ErrorCode::API_SUCCESS,
                'error' => ErrorCode::API_ERROR
            ],
        ];
    }

    /**
     * 初始化配置
     * @return array
     */
    public function actionInit(): array
    {
        $config = [
            'root_role_id' => $this->app->params['root_role_id'],
            'root_dept_id' => $this->app->params['root_dept_id'],
            'root_admin_id' => $this->app->params['root_admin_id']
        ];
        return $this->success('', ['config' => $config]);
    }
}
